import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'video_player_controller.dart' as video_controller;
import '../../function/utils/my_common.dart';

/// 视频播放页面
class VideoPlayerPage extends GetView<video_controller.VideoPlayerController> {
  const VideoPlayerPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: GetX<video_controller.VideoPlayerController>(
        builder: (controller) {
          if (controller.isLoading) {
            return _buildLoadingView();
          }

          if (controller.errorMessage.isNotEmpty) {
            return _buildErrorView(controller);
          }

          if (!controller.isInitialized ||
              controller.videoPlayerController == null) {
            return _buildErrorView(
              controller,
              message: 'Video not initialized',
            );
          }

          return _buildVideoPlayerView(controller);
        },
      ),
    );
  }

  /// 构建加载视图
  Widget _buildLoadingView() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.black,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(MyCommonUtils.green),
              strokeWidth: 3,
            ),
            SizedBox(height: 20.h),
            Text(
              'Loading video...',
              style: TextStyle(
                color: MyCommonUtils.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView(
    video_controller.VideoPlayerController controller, {
    String? message,
  }) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.black,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, color: Colors.red, size: 64.sp),
            SizedBox(height: 20.h),
            Text(
              message ?? controller.errorMessage,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: MyCommonUtils.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 30.h),
            ElevatedButton(
              onPressed: controller.reloadVideo,
              style: ElevatedButton.styleFrom(
                backgroundColor: MyCommonUtils.green,
                foregroundColor: Colors.white,
                padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                'Retry',
                style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w600),
              ),
            ),
            SizedBox(height: 16.h),
            ElevatedButton(
              onPressed: controller.goBack,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.transparent,
                foregroundColor: MyCommonUtils.white,
                side: BorderSide(color: MyCommonUtils.white, width: 1),
                padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                'Go Back',
                style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w600),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建视频播放器视图
  Widget _buildVideoPlayerView(
    video_controller.VideoPlayerController controller,
  ) {
    return GestureDetector(
      onTap: controller.toggleControls,
      child: Stack(
        children: [
          // 视频播放器
          _buildVideoPlayer(controller),

          // 顶部控制栏
          if (controller.showControls)
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: _buildTopControls(controller),
            ),

          // 中央播放按钮
          if (controller.showControls)
            Center(child: _buildCenterPlayButton(controller)),

          // 底部控制栏
          if (controller.showControls)
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: _buildBottomControls(controller),
            ),
        ],
      ),
    );
  }

  /// 构建视频播放器
  Widget _buildVideoPlayer(video_controller.VideoPlayerController controller) {
    return Center(
      child: AspectRatio(
        aspectRatio: controller.videoPlayerController!.value.aspectRatio,
        child: VideoPlayer(controller.videoPlayerController!),
      ),
    );
  }

  /// 构建顶部控制栏
  Widget _buildTopControls(video_controller.VideoPlayerController controller) {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(Get.context!).padding.top + 16.h,
        left: 16.w,
        right: 16.w,
        bottom: 16.h,
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Colors.black.withOpacity(0.7), Colors.transparent],
        ),
      ),
      child: Row(
        children: [
          // 返回按钮
          Container(
            padding: EdgeInsets.all(8.w),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.arrow_back_ios_new,
              color: MyCommonUtils.white,
              size: 20.sp,
            ),
          ).inkWell(onTap: controller.goBack),

          Spacer(),

          // 播放速度按钮
          Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Text(
              '${controller.playbackSpeed}x',
              style: TextStyle(
                color: MyCommonUtils.white,
                fontSize: 12.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ).inkWell(onTap: () => _showSpeedSelector(controller)),
        ],
      ),
    );
  }

  /// 构建中央播放按钮
  Widget _buildCenterPlayButton(
    video_controller.VideoPlayerController controller,
  ) {
    return AnimatedOpacity(
      opacity: controller.isPlaying ? 0.0 : 1.0,
      duration: Duration(milliseconds: 300),
      child: Container(
        width: 80.w,
        height: 80.w,
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.6),
          shape: BoxShape.circle,
        ),
        child: Icon(
          controller.isPlaying ? Icons.pause : Icons.play_arrow,
          color: MyCommonUtils.white,
          size: 40.sp,
        ),
      ).inkWell(onTap: controller.togglePlayPause),
    );
  }

  /// 构建底部控制栏
  Widget _buildBottomControls(
    video_controller.VideoPlayerController controller,
  ) {
    return Container(
      padding: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
        bottom: MediaQuery.of(Get.context!).padding.bottom + 16.h,
        top: 16.h,
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Colors.transparent, Colors.black.withOpacity(0.7)],
        ),
      ),
      child: Row(
        children: [
          // 播放/暂停按钮
          Icon(
            controller.isPlaying ? Icons.pause : Icons.play_arrow,
            color: MyCommonUtils.white,
            size: 24.sp,
          ).inkWell(onTap: controller.togglePlayPause),

          SizedBox(width: 16.w),

          // 时间显示
          GetBuilder<video_controller.VideoPlayerController>(
            builder: (controller) {
              return Text(
                _formatDuration(controller.position) +
                    ' / ' +
                    _formatDuration(controller.duration),
                style: TextStyle(
                  color: MyCommonUtils.white,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w500,
                ),
              );
            },
          ),

          Spacer(),

          // 停止按钮
          Icon(
            Icons.stop,
            color: MyCommonUtils.white,
            size: 24.sp,
          ).inkWell(onTap: controller.stop),
        ],
      ),
    );
  }

  /// 显示播放速度选择器
  void _showSpeedSelector(video_controller.VideoPlayerController controller) {
    final speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];

    Get.bottomSheet(
      Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.9),
          borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              'Playback Speed',
              style: TextStyle(
                color: MyCommonUtils.white,
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
            SizedBox(height: 20.h),
            Wrap(
              spacing: 12.w,
              runSpacing: 12.h,
              children:
                  speeds.map((speed) {
                    final isSelected = speed == controller.playbackSpeed;
                    return Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 8.h,
                      ),
                      decoration: BoxDecoration(
                        color:
                            isSelected
                                ? MyCommonUtils.green
                                : Colors.white.withOpacity(0.2),
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      child: Text(
                        '${speed}x',
                        style: TextStyle(
                          color:
                              isSelected ? Colors.black : MyCommonUtils.white,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ).inkWell(
                      onTap: () {
                        controller.setPlaybackSpeed(speed);
                        Get.back();
                      },
                    );
                  }).toList(),
            ),
            SizedBox(height: 20.h),
          ],
        ),
      ),
      backgroundColor: Colors.transparent,
    );
  }

  /// 格式化时间
  String _formatDuration(Duration? duration) {
    if (duration == null) return '00:00';

    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }
}
